package com.qdc.datacenters.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.qdc.datacenters.domain.entity.*;
import com.qdc.datacenters.domain.query.sensitive.SensitiveQuery;
import com.qdc.datacenters.domain.queue.ChatMsgSensitiveQueue;
import com.qdc.datacenters.domain.vo.group.CorpGroupVo;
import com.qdc.datacenters.event.QwSensitiveEvent;
import com.qdc.datacenters.service.*;
import com.qdc.datacenters.service.impl.ThreadFactoryImpl;
import com.qdc.datacenters.utils.DFAUtil;
import com.qdc.datacenters.utils.ThreadUtils;
import jakarta.annotation.PreDestroy;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * @author danmo
 * @date 2024-03-12 15:21
 **/
@Slf4j
@AllArgsConstructor
@Component
public class QwSensitiveListener implements ApplicationListener<QwSensitiveEvent> {

    private final IChatContactMsgSensitiveService sensitiveService;
    private final ISensitiveWordsResultService wordsResultService;
    private final ICorpPermitUserService iCorpPermitUserService;
    private final ICorpCustomerService iCorpCustomerService;
    private final ICorpGroupService iCorpGroupService;
    private final ThreadPoolExecutor sensitiveExecutor = new ThreadPoolExecutor(3, 5, 10L, MILLISECONDS, new ArrayBlockingQueue<>(1024), new ThreadFactoryImpl("SensitiveThread_"));
    @Override
    public void onApplicationEvent(QwSensitiveEvent event) {
        sensitiveExecutor.execute(() -> {
            ChatMsgSensitiveQueue queue = (ChatMsgSensitiveQueue) event.getSource();
            ChatContactMsg msg = queue.getMsg();
            SensitiveQuery sensitiveQuery = new SensitiveQuery();
            sensitiveQuery.setStatus(1);
            //客户
            if (Objects.equals(3, msg.getOrigin())) {
                sensitiveQuery.setRangeType(1);
                CorpCustomer corpCustomer = iCorpCustomerService.getByExternalUserId(msg.getFromId());
                if(Objects.nonNull(corpCustomer)){
                    sensitiveQuery.setEffectId(corpCustomer.getId());
                }
            }
            //员工
            else if (Objects.equals(5, msg.getOrigin())) {
                sensitiveQuery.setRangeType(2);
                CorpPermitUser permitUser = iCorpPermitUserService.getByCorpUserId(msg.getFromId());
                if(Objects.nonNull(permitUser)){
                    sensitiveQuery.setEffectId(permitUser.getUserId());
                }
            }
            List<ChatContactMsgSensitive> sensitiveList = sensitiveService.getListByEffectId(sensitiveQuery);
            if (CollectionUtil.isNotEmpty(sensitiveList)) {
                for (ChatContactMsgSensitive sensitive : sensitiveList) {
                    List<String> list = Arrays.stream(sensitive.getWords().split(",")).toList();
                    JSONObject dfaHashMap = DFAUtil.createDFAHashMap(new HashSet<>(list));
                    Set<String> words = DFAUtil.getSensitiveWordByDFAMap(dfaHashMap, msg.getMsgText(), 2);
                    if (CollectionUtil.isNotEmpty(words)) {
                        SensitiveWordsResult wordsResult = new SensitiveWordsResult();
                        wordsResult.setStId(sensitive.getId());
                        wordsResult.setMsgId(msg.getId());
                        wordsResult.setWords(String.join(",", words));
                        wordsResult.setSendTime(msg.getMsgTime());
                        wordsResult.setEffectId(sensitiveQuery.getEffectId());
                        if (Objects.equals(3, msg.getOrigin())) {
                            wordsResult.setType(2);
                            if(Objects.equals(1, msg.getChatType())){
                                CorpPermitUser permitUser = iCorpPermitUserService.getByCorpUserId(msg.getToList());
                                if(Objects.nonNull(permitUser)){
                                    wordsResult.setTargetId(permitUser.getUserId());
                                }
                            }
                        } else if (Objects.equals(5, msg.getOrigin())) {
                            wordsResult.setType(1);
                            if(Objects.equals(1, msg.getChatType())){
                                CorpCustomer corpCustomer = iCorpCustomerService.getByExternalUserId(msg.getToList());
                                if(Objects.nonNull(corpCustomer)){
                                    wordsResult.setTargetId(corpCustomer.getId());
                                }
                            }
                        }
                        wordsResult.setChatType(msg.getChatType());
                        if (Objects.equals(2, msg.getChatType())) {
                            CorpGroupVo chatInfo = iCorpGroupService.getByChatId(msg.getRoomId(), msg.getRelationType());
                            wordsResult.setTargetId(chatInfo.getId());
                        }
                        wordsResultService.save(wordsResult);
                    }
                }
            }
        });

    }

    @PreDestroy
    public void shutdown() {
        log.info("敏感词线程池开始注销");
        ThreadUtils.shutdownAndAwaitTermination(sensitiveExecutor);
    }
}
